#!coding:utf-8
'''
Created on Aug 17, 2012

@author: join
'''
from lottery_terminal.common import utils,Constant
import datetime
from lottery_terminal.models import Account, Period, Trade
import logging
from xml.dom.minidom import parseString
from django.http import HttpResponse
from lottery_terminal.view.period import _do_init
from lottery_terminal.service.lotteryservice.baseService import BaseLottery
from lottery_terminal.common.ticketutil import shengxiao_dict,\
    ticket_model_ticket
from lottery_terminal.rpc.rbc import conf_dict
from lottery_terminal.rpc import rbc
import time
import json

LOG = logging.getLogger('terminal')

trademethod_dict = {0:u'刷银联卡',1:u'投币',2:u'人工代购'}
type_dict1 = {Constant.TRADE_ACTION:u'交易中', Constant.TRADE_FAILED:u'交易失败', Constant.TRADE_SUCCESSED:u'交易成功', Constant.TRADE_CENCELED:u'交易取消',Constant.TRADE_POS_FAILED:u'打印彩票失败'}
type_dict2 = {Constant.RECHARGE:u'充值', Constant.BUY_LOTTERY:u'购买彩票', Constant.TO_CASH:u'提现', Constant.BACK_AWARD:'返奖'}
type_dict3 = {Constant.TicketConstant:u'时时彩', Constant.TicketLoan:u'双色球', Constant.SevenColor:u'七乐彩',Constant.ThreeD:u'福彩3D',Constant.FiveBall:u'十五选五',Constant.SixPlusOne:u'东方6+1' }
type_dict4 = {Constant.DANSHI:u'单式', Constant.FUSHI:u'复式', Constant.BAOHAO:u'包号',Constant.HEZHI:u'和值',Constant.DANTUO:u'胆托' }

@utils.render
def index(req):
   
    return 'index.html'

#@utils.render
#def logout(req,mac):
#    session_dict[mac] = ''
#    return 'index.html'

@utils.render
def fifteen_five(req):
    '''十五选五'''
    result = _do_init('15',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fifteen_five_rule'
    result['gg_page'] = 'fifteen_five_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'fifteen_five.html',result


@utils.render
def fifteen_fiveDT(req):
    '''十五选五'''
    result = _do_init('15',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fifteen_five_rule'
    result['gg_page'] = 'fifteen_five_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'fifteen_five_dantuo.html',result


@utils.render
def six_one(req):
    '''东方6+1'''
    result = _do_init('06',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'six_one_rule'
    result['gg_page'] = 'six_one_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'six_one.html',result

@utils.render
def double(req):
    '''双色球'''
    result = _do_init('01',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'double_rule'
    result['gg_page'] = 'double_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'double.html',result


@utils.render
def shishicai(req):
    '''时时彩-一星'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai.html',result


@utils.render
def shishicai_two(req):
    '''时时彩-二星直选'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_two.html',result


@utils.render
def shishicai_two_two(req):
    '''时时彩-二星组选'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_two_two.html',result

@utils.render
def shishicai_three(req):
    '''时时彩-三星直选'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_three.html',result


@utils.render
def shishicai_three_one(req):
    '''时时彩-三星组三'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_three_one.html',result

@utils.render
def shishicai_three_three(req):
    '''时时彩-三星组三'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'shishicai_three_three.html',result

@utils.render
def shishicai_three_two(req):
    '''时时彩-三星组六'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_three_two.html',result


@utils.render
def shishicai_four(req):
    '''时时彩-四星'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'shishicai_four.html',result


@utils.render
def shishicai_five(req):
    '''时时彩-五星直选'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '5'
    return 'shishicai_five.html',result

@utils.render
def shishicai_five_one(req):
    '''时时彩-五星通选'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '1'
    result['sx'] = '5'
    return 'shishicai_five_one.html',result

@utils.render
def shishicai_six(req):
    '''时时彩-大小单双'''
    result = _do_init('20',1)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'ssc_rule'
    result['gg_page'] = 'ssc_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'shishicai_six.html',result

@utils.render
def double_dantuo(req):
    '''双色球——胆托'''
    result = _do_init('01',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'double_rule'
    result['gg_page'] = 'double_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'double_dantuo.html',result


@utils.render
def qilecai(req):
    '''七彩乐'''
    result = _do_init('07',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'qilecai_rule'
    result['gg_page'] = 'qilecai_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'qilecai.html',result


@utils.render
def qilecai_dantuo(req):
    '''七彩乐'''
    result = _do_init('07',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'qilecai_rule'
    result['gg_page'] = 'qilecai_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'qilecai_dantuo.html',result

@utils.render
def fucai3D(req):
    '''福彩3D-直选'''
    result = _do_init('05',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fucai3D_rule'
    result['gg_page'] = 'fucai3D_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'fucai3D.html',result


@utils.render
def fucai3Dzx(req):
    '''福彩3D-直选'''
    result = _do_init('05',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fucai3D_rule'
    result['gg_page'] = 'fucai3D_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'fucai3D.html',result


@utils.render
def fucai3D_3zs(req):
    '''福彩3D-组三'''
    result = _do_init('05',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fucai3D_rule'
    result['gg_page'] = 'fucai3D_anounce'
    result['pd'] = '5'
    result['sx'] = '1'
    return 'fucai3D_3.html',result

@utils.render
def fucai3D_3zs_0(req):
    '''福彩3D-组三单式'''
    result = _do_init('05',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fucai3D_rule'
    result['gg_page'] = 'fucai3D_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'fucai3D_3_0.html',result


@utils.render
def fucai3D_6zl(req):
    '''福彩3D-组六'''
    result = _do_init('05',30)
    if type(result) == tuple:
        err_result = {'err_msg':u'不要走开，彩票即将开售'}
        return '500.html',err_result
    result['rule_page'] = 'fucai3D_rule'
    result['gg_page'] = 'fucai3D_anounce'
    result['pd'] = '1'
    result['sx'] = '1'
    return 'fucai3D_6.html',result


@utils.render
def game_rules(req,href):
    '''游戏规则'''
    return '%s.html'%href

@utils.render
def help_center(req):
    '''帮助中心'''
    return 'help_center.html'

@utils.render
def login(req):
    '''弹出充值的登录页面'''
    return 'login.html'

@utils.render
def guanli(req):
    '''管理的主界面'''
    return 'guanli.html'

@utils.ajaxrender
def chk_login(req):
    '''验证登录帐号和密码'''
    account_number = req.POST.get('acc_num')
    password = req.POST.get('password')
    mac = req.POST.get('mac')
    
    if not account_number or not password:
        return u'请刷额度卡并填写密码',400

    accounts = Account.objects.filter(deleted=False,account=account_number,password=utils.getMD5Str(password),mac=mac)
    if not accounts:
        return u'用户无效，请重试',400
    account = accounts[0]
    result = {'id':account.id}
    return json.dumps(result),200

@utils.render
def show_recharge(req):
    '''店主充值页面'''
    return 'recharge.html'


@utils.render
def gonggao(req,href):
    '''公告展示'''
    result = {}
    now = datetime.datetime.now()
    lotterycode = '01'
    if href == 'double_anounce': #双色球公告
        pass
    elif href == 'ssc_anounce': #时时彩公告
        lotterycode = '20'
    elif href == 'qilecai_anounce': #七乐彩公告
        lotterycode = '07'
    elif href == 'fucai3D_anounce': #福彩3D公告
        lotterycode = '05'
    elif href == 'fifteen_five_anounce': #15选5公告
        lotterycode = '15'
    elif href == 'six_one_anounce': #6+1公告
        lotterycode = '06'
        
    periods = Period.objects.filter(lotterycode=lotterycode,awardtime__lt=now).order_by('-awardtime')[0:5]
    
    baselottery = BaseLottery(lotterycode)
    for period in periods:
        if not period.awardcodes: #.awardtime or not period.poolmoney:
#            baselottery.query_award_code(period.periodid)
            baselottery.query_award_money(period.periodid)
    periods = Period.objects.filter(lotterycode=lotterycode,awardtime__lt=now).order_by('-awardtime')[0:5]

    infos = []
    first = True
    for period in periods:
        periodinfo={}
        periodinfo['periodid'] = period.periodid
        if not period.awardcodes:
            continue
        if lotterycode == '01' or lotterycode == '07':
            periodinfo['red'] = period.awardcodes.split('|')[0].split(',')
#            periodinfo['blue'] = period.awardcodes.split('|')[1]
            periodinfo['blue'] = period.awardcodes.split('|')[1]
        elif lotterycode == '20' or lotterycode == '05' or lotterycode == '15':
            periodinfo['awardcodes'] = period.awardcodes.split(',')
        elif lotterycode == '06':
            periodinfo['red'] = period.awardcodes.split('|')[0].split(',')
            periodinfo['blue'] = shengxiao_dict.get(period.awardcodes.split('|')[1])
        periodinfo['awardtime'] = utils.convert_datetime_to_str(period.awardtime,'%Y-%m-%d %H:%M:%S')
        pool_money = period.poolmoney if period.poolmoney else 0
        if pool_money == 0:
            periodinfo['poolmoney'] = u'无'
        else:
            periodinfo['poolmoney'] = utils.convert_money_number('%s' % pool_money)
            
        if first:
            first = False
            result['latest'] = periodinfo
        else:
            infos.append(periodinfo)

            result['infos'] = infos
    return '%s.html'%href, result
    

def result_receive(req):
    '''彩票出票结果通知'''
    res_xml = '<?xml version="1.0" encoding="gb2312"?><Resp><status>%s</status><desc>%s</desc></Resp>'
    try:
        LOG.info("here start receive ticket message.")
        xml_param = req.POST.get('xml')
        LOG.debug("xml_param is:%s" % xml_param)
        sign = req.POST.get('sign')
        sign_2 = utils.getMD5Str(xml_param + rbc.key)
        if not sign == sign_2.upper():
            LOG.exception('sign error,orginal:%s,our system:%s'%(sign,sign_2))
            return HttpResponse(res_xml%(2,'sign error'))
        xml_param=xml_param.replace('encoding="gb2312"', 'encoding="utf8"')
        dom = parseString(xml_param)
        resp_node = dom.getElementsByTagName("Resp")[0]
        errorcode = resp_node.getAttribute('errcode')
        sd_batchid = resp_node.getAttribute('batchid')
    except Exception as e:
        LOG.exception("an exception occured:%s"%e)
        status_code=2
        desc=u'异常'
        return HttpResponse(res_xml%(status_code,desc))
    try:
        LOG.debug("resp_node is:%s, errorcode is:%s"%(resp_node,errorcode))
        if errorcode == '0':
            LOG.debug("lottery center sales these tickets successfully.")
            Trade.objects.filter(desc=sd_batchid).update(status=2)
            trade = Trade.objects.filter(desc=sd_batchid)[0]
            ticket_model_ticket.get(trade.tradeTicketType).objects.filter(tradeId__desc=sd_batchid).update(status=2)
            status_code = 0
            desc = u'成功'
        else:
            Trade.objects.filter(desc=sd_batchid).update(status=1)
            trade = Trade.objects.filter(desc=sd_batchid)[0]
            ticket_model_ticket.get(trade.tradeTicketType).objects.filter(tradeId__desc=sd_batchid).update(status=1)
            status_code = 0
            desc = u'失败'
        return HttpResponse(res_xml%(status_code,desc))
    except Exception as e:
        LOG.exception("an exception occured:%s"%e)
        status_code=0
        desc=u'异常'
        return HttpResponse(res_xml%(status_code,desc))

@utils.render
def all_qushitu(req):
    return 'all_qushitu.html'

def get_client_version(req):
    '''获取客户端版本号'''
    client_version = conf_dict.get('client.version')
    return HttpResponse(client_version)

def get_sd_result(req,sdbatchid):
    '''福彩中心收单响应结果'''
    try:
        time.sleep(0.01)
        trade = Trade.objects.filter(desc=sdbatchid)[0]
        status = trade.status
            
        return HttpResponse("%s"%status)
    except Exception as e:
        LOG.exception("exception is:%s"%e)
        return HttpResponse('1')
    
def reporterror(req,errormsg):
    LOG.error("erorr report from pos client start")
    LOG.error(errormsg)
    LOG.error("erorr report from pos client end")
    return HttpResponse('1')
